<?php
class Response extends Yaf_Response_Abstract {
    public static function work($data,$type='JSON') {
        switch (strtoupper($type)){
        case 'JSON' :
            $depath=64;
            header('Content-Type:application/json; charset=utf-8');
            echo (json_encode($data,$depath));
            break;
        case 'XML'  :
            header('Content-Type:text/xml; charset=utf-8');
            echo self::xml_encode($data);
        case 'JSONP':
            header('Content-Type:application/json; charset=utf-8');
            echo $handler.'('.json_encode($data).')';
        case 'EVAL' :
            header('Content-Type:text/html; charset=utf-8');
            echo $data;            
        }
    }
    
    public static function xml_encode($data, $item='item', $attr='', $id='id', $encoding='utf-8') {
        if(is_array($attr)){
            $_attr = array();
            foreach ($attr as $key => $value) {
                $_attr[] = "{$key}=\"{$value}\"";
            }
            $attr = implode(' ', $_attr);
        }
        $attr   = trim($attr);
        $attr   = empty($attr) ? '' : " {$attr}";
        $xml    = "<?xml version=\"1.0\" encoding=\"{$encoding}\"?>";
        $xml   .= "<root {$attr}>";
        $xml   .= self::data_to_xml($data, $item, $id);
        $xml   .= "</root>";
        return $xml;
    }
    public static function data_to_xml($data, $item='item', $id='id') {
        $xml = $attr = '';
        foreach ($data as $key => $val) {
            if(is_numeric($key)){
                $id && $attr = " {$id}=\"{$key}\"";
                $key  = $item;
            }
            $xml    .=  "<{$key}{$attr}>";
            $xml    .=  (is_array($val) || is_object($val)) ? data_to_xml($val, $item, $id) : $val;
            $xml    .=  "</{$key}>";
        }
        return $xml;
    }
    public static function success($msg = ''){
        $data = ['status'=> 1,'msg'=>$msg];
        self::work($data);
    }
    public static function error($msg = ''){
        $data = ['status'=> 0,'msg'=>$msg];
        self::work($data);        
    }
                                               
}